package com.engine.salary.web;

import com.engine.common.util.ServiceUtil;
import com.engine.salary.component.WeaFormOption;
import com.engine.salary.entity.salaryitem.dto.SalaryItemFormDTO;
import com.engine.salary.entity.salaryitem.dto.SalaryItemListDTO;
import com.engine.salary.entity.salaryitem.dto.SysSalaryItemListDTO;
import com.engine.salary.entity.salaryitem.param.*;
import com.engine.salary.entity.salaryitem.po.SalaryItemPO;
import com.engine.salary.exception.SalaryRunTimeException;
import com.engine.salary.util.ResponseResult;
import com.engine.salary.util.SalaryI18nUtil;
import com.engine.salary.util.excel.ImportExcelResponse;
import com.engine.salary.util.page.PageInfo;
import com.engine.salary.wrapper.SalaryItemWrapper;
import com.engine.salary.wrapper.SysSalaryItemWrapper;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 薪资项目
 * <p>Copyright: Copyright (c) 2022</p>
 * <p>Company: 泛微软件</p>
 *
 * @author qiantao
 * @version 1.0
 **/
@Slf4j
public class SalaryItemController {

    private SalaryItemWrapper getSalaryItemWrapper(User user) {
        return ServiceUtil.getService(SalaryItemWrapper.class, user);
    }


    private SysSalaryItemWrapper getSysSalaryItemWrapper(User user) {
        return ServiceUtil.getService(SysSalaryItemWrapper.class, user);
    }

    /**********************************自定义薪资项目 start*********************************/

    /**
     * 薪资项目列表
     */
    @POST
    @Path("/list")
    @Produces(MediaType.APPLICATION_JSON)
    public String listSalaryItem(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryItemSearchParam searchParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryItemSearchParam, PageInfo<SalaryItemListDTO>>(request, response, user).run(getSalaryItemWrapper(user)::listPage, searchParam);
    }

    @POST
    @Path("/listAuth")
    @Produces(MediaType.APPLICATION_JSON)
    public String listAuth(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryItemSearchParam searchParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryItemSearchParam, List<SalaryItemPO>>(request, response, user).run(getSalaryItemWrapper(user)::listAuth, searchParam);
    }


    /**
     * 可删除的薪资项目列表
     *
     * @param request
     * @param response
     * @param searchParam
     * @return
     */
    @POST
    @Path("/listCanDelete")
    @Produces(MediaType.APPLICATION_JSON)
    public String listCanDeleteSalaryItem(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryItemSearchParam searchParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryItemSearchParam, PageInfo<SalaryItemListDTO>>(user).run(getSalaryItemWrapper(user)::listPage4CanDelete, searchParam);
    }

    /**
     * 获取多个薪资项目的详情
     *
     * @return
     */
    @POST
    @Path("/listSalaryItemDetail")
    @Produces(MediaType.APPLICATION_JSON)
    public String listSalaryItemDetail(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody Collection<Long> ids) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Collection<Long>, List<SalaryItemListDTO>>(user).run(getSalaryItemWrapper(user)::listByIds, ids);
    }


//    @GetMapping("/getSearchCondition")
//    @ApiOperation("薪资项目列表的高级搜索")
//    @WeaPermission
//    public WeaResult<WeaSearchCondition> getSearchCondition() {
//        return WeaResult.success(salaryItemWrapper.getSearchCondition());
//    }


    /**
     * 薪资项目的详情
     */
    @GET
    @Path("/getSalaryForm")
    @Produces(MediaType.APPLICATION_JSON)
    public String getSalaryItemForm(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam(value = "id") Long id) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, SalaryItemFormDTO>(user).run(getSalaryItemWrapper(user)::getForm, id);
    }

    /**
     * 获取哪些账套中使用了该薪资项目
     */
    @GET
    @Path("/getSalarySobBySalaryItem")
    @Produces(MediaType.APPLICATION_JSON)
    public String getSalarySobBySalaryItem(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam(value = "id") Long id) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Long, List<Map<String, Object>>>(user).run(getSalaryItemWrapper(user)::getSalarySobBySalaryItem, id);
    }

    /**
     * 将薪资项目管理中的信息同步至账套
     */
    @POST
    @Path("/syncSalaryItemToSalarySobItem")
    @Produces(MediaType.APPLICATION_JSON)
    public String syncSalaryItemToSalarySobItem(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SyncSalaryItemParam param) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SyncSalaryItemParam, String>(user).run(getSalaryItemWrapper(user)::syncSalaryItemToSalarySobItem, param);
    }

    /**
     * "获取薪资项目可选的类型（与属性有联动）"
     *
     * @return
     */
    @GET
    @Path("/listSalaryItemTypeOption")
    @Produces(MediaType.APPLICATION_JSON)
    public String listSalaryItemTypeOption(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<String, Map<String, List<WeaFormOption>>>(user).run(getSalaryItemWrapper(user)::listSalaryItemTypeOption);
    }

    /**
     * 删除
     */
    @POST
    @Path("/delete")
    @Produces(MediaType.APPLICATION_JSON)
    public String deleteSalaryItem(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody Collection<Long> ids) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<Collection<Long>, String>(user).run(getSalaryItemWrapper(user)::delete, ids);
    }

    /**
     * 保存薪资项目
     */
    @POST
    @Path("/save")
    @Produces(MediaType.APPLICATION_JSON)
    public String saveSalaryItem(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryItemSaveParam saveParam) {
        User user = HrmUserVarify.getUser(request, response);
        if (saveParam.getId() == null || saveParam.getId() <= 0) {
            return new ResponseResult<SalaryItemSaveParam, String>(request, response, user).run(getSalaryItemWrapper(user)::save, saveParam);
        } else {
            return new ResponseResult<SalaryItemSaveParam, String>(request, response, user).run(getSalaryItemWrapper(user)::update, saveParam);
        }
    }

    /**
     * 更新薪资项目
     */
    @POST
    @Path("/update")
    @Produces(MediaType.APPLICATION_JSON)
    public String updateSalaryItem(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryItemSaveParam saveParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryItemSaveParam, String>(user).run(getSalaryItemWrapper(user)::update, saveParam);
    }


    @POST
    @Path("/export")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response export(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryItemExportParam param) {
        try {
            User user = HrmUserVarify.getUser(request, response);
            XSSFWorkbook workbook = getSalaryItemWrapper(user).export(param);
            String time = LocalDate.now().toString();
            String fileName = "薪资项目" + time;
            try {
                fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            StreamingOutput output = outputStream -> {
                workbook.write(outputStream);
                outputStream.flush();
            };
            response.setContentType("application/octet-stream");
            return Response.ok(output).header("Content-disposition", "attachment;filename=" + fileName).header("Cache-Control", "no-cache").build();
        } catch (Exception e) {
            log.error("薪资项目下载失败", e);
            throw e;
        }
    }

    @POST
    @Path("/downloadTemplate")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response downloadTemplate(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryItemDownloadTemplateParam param) {
        try {
            User user = HrmUserVarify.getUser(request, response);
            XSSFWorkbook workbook = getSalaryItemWrapper(user).downloadTemplate(param);
            String time = LocalDate.now().toString();
            String fileName = "薪资项目导入模板" + time;
            try {
                fileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            StreamingOutput output = outputStream -> {
                workbook.write(outputStream);
                outputStream.flush();
            };
            response.setContentType("application/octet-stream");
            return Response.ok(output).header("Content-disposition", "attachment;filename=" + fileName).header("Cache-Control", "no-cache").build();
        } catch (Exception e) {
            log.error("薪资项目导入模板", e);
            throw e;
        }
    }

    @POST
    @Path("/preview")
    @Produces(MediaType.APPLICATION_JSON)
    public String preview(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryItemImportParam importParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryItemImportParam, Map<String, Object>>(user).run(getSalaryItemWrapper(user)::preview, importParam);
    }

    @POST
    @Path("/import")
    @Produces(MediaType.APPLICATION_JSON)
    public String importSalaryItem(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SalaryItemImportParam importParam) {
        User user = HrmUserVarify.getUser(request, response);
        return new ResponseResult<SalaryItemImportParam, ImportExcelResponse>(user).run(getSalaryItemWrapper(user)::importSalaryItem, importParam);
    }

    /**********************************自定义薪资项目 end*********************************/


    /**********************************系统薪资项目 start*********************************/


    /**
     * 系统薪资项目列表
     */
    @POST
    @Path("/sysList")
    @Produces(MediaType.APPLICATION_JSON)
    public String listSysSalaryItem(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody SysSalaryItemSearchParam searchParam) {
        User user = HrmUserVarify.getUser(request, response);

        return new ResponseResult<SysSalaryItemSearchParam, PageInfo<SysSalaryItemListDTO>>(user).run(getSysSalaryItemWrapper(user)::listPage, searchParam);
    }


//    @GetMapping("/getSysSearchCondition")
//    @ApiOperation("系统薪资项目的高级搜索")
//    @WeaPermission
//    public WeaResult<WeaSearchCondition> getSysSearchCondition() {
//        return WeaResult.success(sysSalaryItemWrapper.getSearchCondition());
//    }


    /**
     * 添加系统薪资项目
     */
    @POST
    @Path("/saveSys")
    @Produces(MediaType.APPLICATION_JSON)
    public String saveSysSalaryItem(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody Collection<Long> sysSalaryItemIds) {
        User user = HrmUserVarify.getUser(request, response);
        if (CollectionUtils.isEmpty(sysSalaryItemIds)) {
            throw new SalaryRunTimeException(SalaryI18nUtil.getI18nLabel(84026, "参数错误"));
        }
        return new ResponseResult<Collection<Long>, Map<String, Object>>(user).run(getSysSalaryItemWrapper(user)::add2SalaryItem, sysSalaryItemIds);
    }

//    /**********************************系统薪资项目 end*********************************/
}
